// 当前题库数据
let currentQuestions = {};

// DOM 元素
const positionSelect = document.getElementById('positionSelect');
const fileUpload = document.getElementById('fileUpload');
const questionContent = document.getElementById('questionContent');
const answerContent = document.getElementById('answerContent');

// 加载JSON文件中的题目
async function loadQuestionsFromJson(position) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `questions/${position}.json`, true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    const data = JSON.parse(xhr.responseText);
                    currentQuestions[position] = data;
                    resolve(true);
                } catch (error) {
                    console.error('解析题目失败：', error);
                    resolve(false);
                }
            } else {
                console.error('加载题目失败');
                resolve(false);
            }
        };
        xhr.onerror = function() {
            console.error('加载题目失败');
            resolve(false);
        };
        xhr.send();
    });
}

// 显示随机题目
// 添加模式切换功能
const modeToggle = document.getElementById('modeToggle');
const answerPanel = document.getElementById('answerPanel');
const questionCount = document.getElementById('questionCount');

// 模式切换监听
modeToggle.addEventListener('change', () => {
    if (modeToggle.checked) {
        answerPanel.classList.remove('hidden');
    } else {
        answerPanel.classList.add('hidden');
    }
});

// 添加已使用题目的追踪
let usedQuestionIndices = new Set();

// 获取随机不重复题目索引
function getRandomUniqueIndex(maxValue, excludeIndices) {
    let availableIndices = [];
    for (let i = 0; i < maxValue; i++) {
        if (!excludeIndices.has(i)) {
            availableIndices.push(i);
        }
    }
    
    if (availableIndices.length === 0) {
        // 如果所有题目都用过了，重置已使用集合
        excludeIndices.clear();
        return Math.floor(Math.random() * maxValue);
    }
    
    const randomIndex = Math.floor(Math.random() * availableIndices.length);
    return availableIndices[randomIndex];
}

// 修改显示随机题目函数
function showRandomQuestion() {
    const position = positionSelect.value;
    const questions = currentQuestions[position]?.questions;
    if (!questions || questions.length === 0) return;

    const count = parseInt(questionCount.value);
    let content = '';
    let answers = '';
    let currentQuestionIndices = new Set();

    // 清空已使用题目集合（当切换题目数量或岗位时）
    if (count === 1) {
        usedQuestionIndices = new Set();
    }

    for (let i = 0; i < count; i++) {
        let randomIndex;
        do {
            randomIndex = getRandomUniqueIndex(questions.length, 
                count === 1 ? usedQuestionIndices : currentQuestionIndices);
        } while (currentQuestionIndices.has(randomIndex));

        currentQuestionIndices.add(randomIndex);
        if (count === 1) {
            usedQuestionIndices.add(randomIndex);
        }

        const { question, answer } = questions[randomIndex];
        content += `${i + 1}. ${question}\n\n`;
        answers += `${i + 1}. ${answer}\n\n`;
    }

    questionContent.textContent = content;
    answerContent.textContent = answers;
}

// 处理Excel文件上传
fileUpload.addEventListener('change', async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async (e) => {
        try {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
            const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: ['question', 'answer'] });

            if (jsonData.length > 0) {
                jsonData.shift();
            }

            const newPosition = file.name.replace(/\.[^/.]+$/, '').toLowerCase();
            
            const option = document.createElement('option');
            option.value = newPosition;
            option.textContent = file.name.replace(/\.[^/.]+$/, '');
            positionSelect.appendChild(option);

            currentQuestions[newPosition] = {
                questions: jsonData
            };

            positionSelect.value = newPosition;
            showRandomQuestion();

            alert('文件上传成功！');
        } catch (error) {
            console.error('文件处理错误：', error);
            alert('文件处理失败，请确保Excel格式正确！');
        }
    };

    reader.readAsArrayBuffer(file);
});

// 监听岗位选择变化
positionSelect.addEventListener('change', async () => {
    const position = positionSelect.value;
    if (!currentQuestions[position]) {
        const loaded = await loadQuestionsFromJson(position);
        if (loaded) {
            showRandomQuestion();
        }
    } else {
        showRandomQuestion();
    }
});

// 点击题目面板随机切换题目
questionContent.addEventListener('click', showRandomQuestion);

// 点击下一题按钮随机切换题目
document.getElementById('nextButton').addEventListener('click', showRandomQuestion);

// 初始加载HR岗位的题目并显示
loadQuestionsFromJson('hr').then(() => {
    showRandomQuestion();
});

// 初始显示一个随机题目
showRandomQuestion();